package com.mhs.expression;

import com.mhs.vo.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 自定义SecurityExpressionRoot权限认证方法
 */
@Component("fse") // 将Bean命名,方便使用
public class FantasySecurityExpressionRoot {

    /**
     * 验证当前LoginUser是否有authority权限
     *
     * @param authority 权限 本系统可取admin user doctor
     * @return
     */
    public boolean hasAuthority(String authority) {
        //获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();
        //判断用户权限集合中是否存在authority
        return permissions.contains(authority); //存在返回true
    }

    /**
     * 验证当前LoginUser是否有authorities权限中的任意一个
     * @param authorities 一个或多个权限 本系统可取admin user doctor
     * @return
     */
    public boolean hasAnyAuthority(String... authorities) {

        //获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();
        //判断用户权限集合中是否存在authorities中的任意一个
        String[] strings = authorities;
        for (String string : strings) {
            return permissions.contains(string); //存在返回true
        }
        return false;
    }
    
    
}